package com.example.victory.service;

import com.example.victory.entity.companyEntity.ContractExpireEntity;
import com.example.victory.mapper.CustomerMapper;
import com.example.victory.swagger.handler.MiniAppContractExpireApiDelegate;
import com.example.victory.swagger.model.*;
import com.example.victory.utils.CrmUtils;
import com.cgws.fintech.sdk.api.mvp.model.ApiRequestCustomerQueryData;
import com.cgws.fintech.sdk.api.mvp.model.CustomerAccount;
import com.cgws.fintech.sdk.common.utils.DateHelper;
import com.example.victory.common.web.ServiceHelper;
import com.cgws.fintech.sdk.inner.utils.web.SessionService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class MiniappContractExpireService implements MiniAppContractExpireApiDelegate {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private MvpLoginService mvpLoginService;
    @Autowired
    private SessionService sessionService;
    @Value("${app.is.crm.product:true}")
    private boolean isCrmProduct;

    @Override
    public ResponseEntity<ApiResponseContractExpire> getContractExpire(ApiRequestContractExpire param) {
        ApiRequestContractExpireData data = param.getData();
        ServiceHelper.checkDataNotNull(data, "data");
        Integer dateRange = data.getDateRange();
        if (dateRange == null) dateRange = 1;
        Date date = new Date();
        String startDate = DateHelper.getDateYYYYMMDD(date);
        String endDate = DateHelper.getDateYYYYMMDD(DateHelper.increment(date, dateRange, Calendar.MONTH));

        // 因为测试环境里未来3个月到期的没有数据，所以测试环境查询的是未来3年的数据
        if (!isCrmProduct) {
            endDate = DateHelper.getDateYYYYMMDD(DateHelper.increment(date, 36, Calendar.MONTH));
        }

        // 获取ryid
        Integer ryid = CrmUtils.getCustomerAccount(sessionService.getCurrentUserSession(true).getUser());
        List<ContractExpireEntity> entityList = customerMapper.getContractExpire(ryid, data, startDate, endDate);

        ApiResponseContractExpireData responseContractExpireData = new ApiResponseContractExpireData();
        if (entityList == null || entityList.size() == 0) {
            return ResponseEntity.ok(new ApiResponseContractExpire().data(responseContractExpireData.items(Collections.emptyList())));
        }

        List<ApiRequestCustomerQueryData> customerQueryDataList = Lists.newArrayList();
        List<ContractExpire> custInfoList = new ArrayList<>();
        entityList.forEach(entity -> {
            ApiRequestCustomerQueryData customerQueryData=new ApiRequestCustomerQueryData();
            customerQueryData.setCustNum(entity.getCustomerId());
            customerQueryDataList.add(customerQueryData);

            ContractExpire contractExpire = new ContractExpire();
            contractExpire.setName(entity.getName());
            contractExpire.setCustomerId(entity.getCustomerId());
            contractExpire.setPhone(entity.getPhone());

            ArrayList<KeyValueDetail> keyValueList = Lists.newArrayList();
            KeyValueDetail contractPattern = new KeyValueDetail();
            contractPattern.setName("签约模式");
            if (Objects.equals(entity.getContractPattern(), 1))
                contractPattern.setValue("签约投顾");
            else if (Objects.equals(entity.getContractPattern(), 3))
                contractPattern.setValue("签约产品");
            keyValueList.add(contractPattern);

            KeyValueDetail chargePattern = new KeyValueDetail();
            chargePattern.setName("收费模式");
            chargePattern.setValue(getChargePattern(entity.getChargePattern()));
            keyValueList.add(chargePattern);

            KeyValueDetail effectiveDate = new KeyValueDetail();
            effectiveDate.setName("生效日期");
            effectiveDate.setValue(entity.getEffectiveDate());
            keyValueList.add(effectiveDate);

            KeyValueDetail expireDate = new KeyValueDetail();
            expireDate.setName("截止日期");
            expireDate.setValue(entity.getExpireDate());
            keyValueList.add(expireDate);

            contractExpire.setDetails(keyValueList);
            custInfoList.add(contractExpire);
        });

        if(customerQueryDataList.size()>0){
            List<CustomerAccount> customerAccountList = CrmUtils.getCustAccountListByIds(mvpLoginService, customerQueryDataList);
            if (customerAccountList != null) {
                custInfoList.forEach(customer -> {
                    customerAccountList.forEach(customerAccount->{
                        if(!StringUtils.isEmpty(customerAccount.getFcid())&&customer.getCustomerId().equals(customerAccount.getCustNum())){
                            customer.setImId(customerAccount.getFcid());
                        }
                    });
                });
            }
        }
        return ResponseEntity.ok(new ApiResponseContractExpire().data(responseContractExpireData.items(custInfoList)));
    }


    private String getChargePattern(Integer chargePattern) {
        String chargePatternCN = "";
        switch (chargePattern) {
            case 1:
                chargePatternCN = "免费";
                break;
            case 2:
                chargePatternCN = "账户管理费";
                break;
            case 3:
                chargePatternCN = "差额佣金费率";
                break;
            case 4:
                chargePatternCN = "定额收费";
                break;
            case 5:
                chargePatternCN = "银行卡扣费";
                break;
        }
    return chargePatternCN;
    }
}
